/**
 * Created by leiweibo on 6/28/15.
 */

'use strict'
var app = angular.module('patientcontroller', []);

app.filter('offset', function () {
  return function (input, start) {
    start = parseInt(start, 10);
    return input.slice(start);
  };
});

var countMap = {};
var get_patient_uploader = function(obj, brwoswerBtnStr, container, percentage) {
  var options = {
    'expiration': Math.floor(new Date().getTime() / 1000) + 86400,
    bucket: 'vistrack-attach-prd',
    'save-key': '/{filemd5}{.suffix}'
  };
  // 查看更多参数：http://docs.upyun.com/api/form_api/#表单API接口简介
  var policy = window.btoa(JSON.stringify(options));
  // 从 UPYUN 用户管理后台获取表单 API
  //  var form_api_secret = 'uWXYXiFzo9SwavwderRAIyYJCjg=';
  var form_api_secret = '5ri+TpAfi0lw+O9eaH9PBMYoSHI=';
  // 计算签名
  var signature = md5(policy + '&' + form_api_secret);
  var url_prefix = "http://" + options.bucket + ".b0.upaiyun.com";
  var uploader = new plupload.Uploader({
    runtimes: 'html5,flash,silverlight,html4',
    browse_button: brwoswerBtnStr, // you can pass in id...
    container: document.getElementById(container),
    flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
    silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
    multi_selection:false,
    url: 'http://v0.api.upyun.com/' + options.bucket,

    multipart_params: {
      'Filename': '${filename}', // adding this to keep consistency across the runtimes
      'Content-Type': '',
      'policy': policy,
      'signature': signature
    },

    init: {
      PostInit: function () {
        //do nothing here.
      },

      FilesAdded: function (up, files) {
        plupload.each(files, function (file) {
          uploader.start();
        });
      },

      UploadProgress: function (up, file) {
        if ($("#" + percentage) && $("#" + percentage).size() > 0) {
          $("#" + percentage).text(file.percent + "%");
        } else {
          $('#percentage').text(file.percent + "%");
        }

      },

      FileUploaded: function (up, file, info) {
        var response = JSON.parse(info.response);
        //array.push(url_prefix + response.url);
        obj.url = url_prefix + response.url;
      },

      Error: function (up, err) {
        $("#" + percentage).text("上传失败");
      }
    }
  });
  uploader.init();
  //if (!countMap[brwoswerBtnStr]) {
  //  uploader.init();
  //  countMap[brwoswerBtnStr] = 1;
  //}
}


app.controller('PatientCtrl', function($scope, $window, $filter, $compile, PatientService, DiseaseService, ProvinceService, HospitalService, OfficeService, DoctorService, $routeParams, PatientData) {
  $scope.before_examines_url = {};
  $scope.before_checks_url = {};
  $scope.before_evaluations_url = {};
  $scope.before_complaints_url = {};

  $scope.examinecount = 0;
  $scope.checkcount = 0;
  $scope.evaluationcount = 0;
  $scope.complaintcount = 0;

  $scope.$watch('firstvistime', function (newValue) {
    $scope.firstvistime = $filter('date')(newValue, 'yyyy/MM/dd');
  });

  $scope.$watch('start', function (newValue) {
    $scope.start = $filter('date')(newValue, 'yyyy/MM/dd');
  });

  $scope.$watch('end', function (newValue) {
    $scope.end = $filter('date')(newValue, 'yyyy/MM/dd');
  });

  $scope.add_patient = function() {
    PatientData.set(null);
    window.location = "#/add_patient";
  }

  $scope.export_patient = function() {
    PatientService.export_patient($scope.provinceId, $scope.hospitalId, $scope.diseaseId, $scope.start, $scope.end, function(data, status, headers) {
      var type = headers('Content-Type');
      var defaultFileName = '';
      var disposition = headers('Content-Disposition');
      if (disposition) {
        var match = disposition.match(/.*filename=\"?([^;\"]+)\"?.*/);
        if (match[1])
          defaultFileName = match[1];
      }
      defaultFileName = defaultFileName.replace(/[<>:"\/\\|?*]+/g, '_');
      var blob = new Blob([data], { type: type });
      //saveAs(blob, defaultFileName);
      //deferred.resolve(defaultFileName);

      var fileURL = URL.createObjectURL(blob);
      var a         = document.createElement('a');
      a.href        = fileURL;
      a.target      = '_blank';
      a.download    = '病人记录.xls';
      document.body.appendChild(a);
      a.click();

    });
  }

  $scope.genders = [
    {code: 1, desc: '男'},
    {code: 2, desc: '女'}
  ];

  var data = PatientData.get();
  if (data && !$.isEmptyObject(data)) {
    $scope.id = data._id;
    $scope.username = data.name;
    $scope.weight = data.weight;
    $scope.height = data.height;
    $scope.gender = data.gender;
    $scope.age = data.age;
    $scope.cardno = data.cardno;
    $scope.phone = data.phone;
    $scope.firstvistime = data.firstvistime;
    $scope.province = data.province;

    HospitalService.list_by_province(data.province, function (res) {
      if (res.result == false) {
        $scope.error_msg = res.message;
      }
      $scope.hospitals = res.hospitals;
    });
    $scope.hospital = data.hospital;

    OfficeService.list_by_hospital(data.hospital, function (res) {
      if (res.result == false) {
        $scope.error_msg = res.message;
      }
      $scope.offices = res.offices;
    });
    $scope.office = data.office;
    DoctorService.list_by_office(data.office, function(res) {
      if (res.result == false) {
        $scope.error_msg = res.message;
      }
      $scope.doctors = res.doctors;
    });
    $scope.doctor = data.doctor._id;
    //
    $scope.disease = data.disease;
    //
    $scope.chief_complaint = data.chief_complaint
    $scope.diagnosis = data.diagnosis

    //
    $scope.operation_solution = data.operation_solution
    $scope.abioc_solution = data.abioc_solution
    $scope.wzblood = data.wzblood
    $scope.plt = data.plt
    $scope.wz_volume = Number(data.wz_volume) == 0 ? "":Number(data.wz_volume)
    $scope.treat_times = data.treat_times
    $scope.boneblood = data.boneblood
    $scope.cell= data.cell
    $scope.cell_volume = Number(data.cell_volume) == 0 ? "":Number(data.cell_volume)
    $scope.cell_treat_times = data.cell_treat_times
    $scope.comment = data.comment
    $scope.feedback = data.feedback

    var cca= data.chief_complaint_attach;
    if (cca) {
      $scope.before_complaint_desc = cca.desc
      if (cca.url) {
        $scope.before_complaints_url.url = cca.url;
        var htmlTxt = $compile("<a target='_blank' href=" + cca.url + ">查看</a>")($scope);
        $("#percentage_complaint").html(htmlTxt);
      }
    }

    var be = data.before_evaluation;
    if (be) {
      $scope.before_evaluation_desc = be.desc
      if (be.url) {

        $scope.before_evaluations_url.url = be.url;
        var htmlTxt = $compile("<a target='_blank' href=" + be.url + ">查看</a>")($scope);
        $("#percentage_evaluation").html(htmlTxt);
      }
    }

    var bc = data.before_check;
    if (bc) {
      $scope.before_check_desc = bc.desc
      if (bc.url) {

        $scope.before_checks_url.url = bc.url;
        var htmlTxt = $compile("<a target='_blank' href=" + bc.url + ">查看</a>")($scope);
        $("#percentage_check").html(htmlTxt);
      }
    }

    var be2 = data.before_examin;
    if (be2) {
      $scope.before_examine_desc = be2.desc
      $scope.before_examines_url.url = be2.url;
      if (be2.url) {
        var htmlTxt = $compile("<a target='_blank' href=" + be2.url + ">查看</a>")($scope);
        $("#percentage_examine").html(htmlTxt);
      }
    }
  }


  get_patient_uploader($scope.before_checks_url, 'browser_check', 'container_check', 'percentage_check');
  get_patient_uploader($scope.before_examines_url, 'browser_examine', 'container_examine', 'percentage_examine');
  get_patient_uploader($scope.before_evaluations_url, 'browser_evaluation', 'container_evaluation', 'percentage_evaluation');
  get_patient_uploader($scope.before_complaints_url, 'browser_complaint', 'container_complaint', 'percentage_complaint');

  var getSessionStorageId = function(sessionValue) {
    if (sessionValue == 'null' || sessionValue == 'undefined') {
      return null
    }
    return sessionValue
  }

  $scope.role = $window.sessionStorage.role;
  $scope.hospitalId = getSessionStorageId($window.sessionStorage.search_hospitalId);
  $scope.provinceId = getSessionStorageId($window.sessionStorage.search_provinceId);
  $scope.diseaseId  = getSessionStorageId($window.sessionStorage.search_diseaseId);

  $scope.provinces = ProvinceService.list(function(data) {
    $scope.provinces = data.provinces
  });

  $scope.diseases = DiseaseService.list(function(data) {
    $scope.diseases = data.diseases;
  });

  $scope.provinceChanged = function(provinceId) {
    $scope.hospitals = HospitalService.list_by_province(provinceId, function(res) {
      if (res.result == false) {
        $scope.error_msg = res.message;
      }
      $scope.hospitals = res.hospitals;
    });
  }

  if ($scope.provinceId) {
    $scope.provinceChanged($scope.provinceId)
  }

  $scope.hospitalChanged = function (hospitalId) {
    OfficeService.list_by_hospital(hospitalId, function (res) {
      if (res.result == false) {
        $scope.error_msg = res.message;
      }

      $scope.offices = res.offices;
    });
  };


  $scope.officeChanged = function(officeId) {
    DoctorService.list_by_office(officeId, function(res) {
      if (res.result == false) {
        $scope.error_msg = res.message;
      }

      $scope.doctors = res.doctors;
    });
  };


  if ($scope.role == 4 ) {
    $scope.hospital = $window.sessionStorage.hospital;
    if($scope.hospital) {
      $scope.hospitalChanged($scope.hospital);
    }
  }

  $scope.editPatient = function(pos) {
    var targetPatient = $scope.displayed[pos];
    PatientData.set(targetPatient);
    window.location = "#/update_patient";
  }

  $scope.deletePatient = function(pos) {
    bootbox.setDefaults("locale", "zh_CN");
    bootbox.confirm("确定删除该病人信息吗", function (result) {
      if (result == true) {
        var targetPatient = $scope.displayed[pos];
        if (targetPatient) {
          var data = {id: targetPatient._id};
          PatientService.delete(data, function (res) {
            if (res.result == true) {
              $scope.displayed.splice(pos, 1);
            } else {
              alert('删除数据失败');
            }
          }, function (data, status) {
          });
        } else {
          alert("请刷新重试");
        }
      }
    });
  }

  $scope.submit = function() {
    var examineAttachment = new Attachment($scope.before_examine_desc, $scope.before_examines_url.url)
    var checkAttachment = new Attachment($scope.before_check_desc, $scope.before_checks_url.url)
    var evaluationAttachment = new Attachment($scope.before_evaluation_desc, $scope.before_evaluations_url.url)
    var chiefComplaintAttachment = new Attachment($scope.before_complaint_desc, $scope.before_complaints_url.url)
    var formData = {
      id: $scope.id,
      name: $scope.username,
      gender: $scope.gender,
      height: $scope.height,
      weight: $scope.weight,
      age: $scope.age,
      cardno: $scope.cardno,
      phone: $scope.phone,
      firstvistime: $scope.firstvistime,
      province: $scope.province,
      hospital: $scope.hospital,
      office: $scope.office,
      doctor: $scope.doctor,
      disease: $scope.disease,
      chief_complaint: $scope.chief_complaint,
      chief_complaint_attach: chiefComplaintAttachment,
      diagnosis: $scope.diagnosis,
      before_examin: examineAttachment,
      before_check: checkAttachment,
      before_evaluation: evaluationAttachment,
      operation_solution: $scope.operation_solution,
      abioc_solution: $scope.abioc_solution,
      wzblood: $scope.wzblood,
      plt: $scope.plt,
      wz_volume: $scope.wz_volume,
      treat_times: $scope.treat_times,
      boneblood: $scope.boneblood,
      cell: $scope.cell,
      cell_volume: $scope.cell_volume,
      cell_treat_times: $scope.cell_treat_times,
      feedback: $scope.feedback,
      comment: $scope.comment
    }

    console.log(formData)

    if ($scope.id) {
      PatientService.update(formData, function(res) {
        if (res.result == true) {
          window.location = "#/patient_list";
        } else {
          $scope.error_msg = res.message;
        }
      }, function(data, status) {
        $scope.error_msg = '无权限进行此操作';
      });
    } else {
      PatientService.create(formData, function(res) {
        if (res.result == true) {
          alert('添加病人信息成功！');

          delete $scope.username;
          delete $scope.gender;
          delete $scope.age;
          delete $scope.height;
          delete $scope.weight;
          delete $scope.cardno;
          delete $scope.phone;
          delete $scope.firstvistime;
          delete $scope.province;
          delete $scope.hospital;
          delete $scope.hospital;
          delete $scope.office;
          delete $scope.doctor;
          delete $scope.disease;
          delete $scope.chief_complaint;
          delete $scope.chief_complaint_attach
          delete $scope.diagnosis;
          delete $scope.operation_solution;
          delete $scope.abioc_solution;
          delete $scope.wzblood;
          delete $scope.plt;
          delete $scope.wz_volume;
          delete $scope.treat_times;
          delete $scope.boneblood;
          delete $scope.cell;
          delete $scope.fee;
          delete $scope.cell_volume;
          delete $scope.cell_treat_times;
          delete $scope.before_examine_desc;
          delete $scope.before_check_desc;
          delete $scope.before_evaluation_desc;
          delete $scope.before_complaint_desc;
          delete $scope.comment;
          delete $scope.feedback;
          delete $scope.error_msg

          $('div[id^=percentage_]').text('');

        } else {
          $scope.error_msg = res.message;
        }
      }, function(data, status) {
        $scope.error_msg = '无权限进行此操作';
      });
    }
  }

  var pageState;

  $scope.search = function() {
    var start = $scope.start;
    var end = $scope.end;
    if (start && end) {
      if (new Date(end) < new Date(start))  {
        alert('结束时间不能小于起时时间！');
        return;
      }
    }
    $window.sessionStorage.search_provinceId = $scope.provinceId;
    $window.sessionStorage.search_hospitalId = $scope.hospitalId;
    $window.sessionStorage.search_diseaseId = $scope.diseaseId;
    $window.sessionStorage.search_start = $scope.start;
    $window.sessionStorage.search_end = $scope.end;

    $scope.callServer()
  }

  $scope.cancel = function () {
    PatientData.set(null);
    window.location = '#/patient_list';
  }

  $scope.callServer = function(tableState) {
    $scope.isLoading = true;

    if (!tableState) {
      tableState = pageState
    } else {
      pageState = tableState;
    }
    var pagination = tableState.pagination;
    var pageSize = pagination.number || 20;
    var pageNo = Math.ceil((pagination.start + 1) / pageSize) || 1;

    PatientService.list_by_hospital(
      pageNo, pageSize,
      $scope.provinceId,
      $scope.hospitalId,
      $scope.diseaseId,
      $scope.start,
      $scope.end,
      function(result) {
        $scope.displayed = result.patients;
        tableState.pagination.numberOfPages = result.pageCount;
        $scope.isLoading = false;
      });

  }


});


var Attachment = function(desc, url) {
  this.url = url;
  this.desc = desc;
}
var transformToArray = function(descArr) {
  var arr = Object.keys(descArr).map(function (key) {return descArr[key]});
  return arr;
}